/**
 * @description: token验证
 */

import jwt from 'jsonwebtoken';

export const TokenValidate = () => async (ctx, next) => {
  const { authorization } = ctx.request.header

  if (!authorization) {
    ctx.fail(400, '请先登录')

    return;
  }

  //验证
  let token = authorization.replace('Bearer ', '');
  try {
    const user = jwt.verify(token, process.env.JWT_SCRET);
    ctx.state.user = user;
  } catch (err) {
    ctx.fail(401, '请先登录')
    return;
  }
  await next();
}

